import {connect} from 'react-redux'
import {LoginAction}  from '../../store/actions'

import React, { useState,useEffect, useRef } from 'react'
import {request} from '../../network/request'

import Qs from 'qs'
import { List, InputItem, Button, Toast ,WingBlank,Checkbox } from 'antd-mobile';
import { createForm } from 'rc-form';

import './login.css'
import usr_avatar from '../../statics/img/usr.svg'
import pwd_avatar from '../../statics/img/pwd.svg'
import verify_code from '../../statics/img/verifycode.svg'

const Item = List.Item;
const AgreeItem = Checkbox.AgreeItem;


const BasicInput = (props) => {
  
  const { getFieldProps, getFieldError } = props.form;
  const {verifycodeurl,changeimg,seterrorimg} =props

  const myRef = useRef()

  const [rememberMe , setrememberMe] = useState(false)
  const  onSubmit = () => {
        
        props.form.validateFields({ force: true }, (error) => {
          if (!error) {
            const list_data = {
              ...props.form.getFieldsValue(),
              rememberMe
            }
            //console.log(list_data);
            const {setusrinfo} = props
            const userdata =Qs.stringify({
             ...list_data
            })
           
            request({
                url: 'user/login',
                method: 'post',
                data: userdata
              }).then(
                res=>{
                  console.log(res);
                  switch (res.code){
                    case 901 : Toast.fail('验证码过期,请刷新验证码') ;break
                    case 902 : Toast.fail('验证码错误') ;changeimg(); myRef.current.clearInput();break
                    case 903 : Toast.fail('用户不存在') ;break
                    case 904 : Toast.fail('密码错误') ; break
                    case 200 : 
                       
                        const usrdata = {
                          username: res.data.username,
                          identity: res.data.identity,
                          avatar : res.data.avatar,
                        }
                        setusrinfo(usrdata);
                        Toast.success('登录成功');  
                        props.history.push('/main/profile');
                        break 
                    default : Toast.info('其他错误') 
                  }
                })
          } else {
    
               
              
          }
        });
      }

  const onRegister = () => {
        props.history.push({pathname:'/register'})
      }
  
  useEffect(()=>{

    const {setusrinfo} = props
    //记住我
    request({
      url: 'user/login',
      method: 'post',
    }).then(
      
      res=>{
        
        if(res&&res.code === 200){
          const usrdata = {
            username: res.data.username,
            identity: res.data.identity,
            avatar : res.data.avatar,
          }
          setusrinfo(usrdata);
          Toast.success('登录成功');  
          props.history.push('/main/profile');
        }
        else if (res.code === 900){
          Toast.info('登录失败，请重新输入账号密码');  
        }
        else {
          seterrorimg()
          console.log('网络错误');
        }
      })
  },[])

  
  return (
    <div className = 'login' >
        <List
              renderHeader={() => '请填写登录信息'}
              renderFooter={() => getFieldError('username') && getFieldError('username').join(',')}
        >
        <InputItem
          {...getFieldProps('username', {
            
            rules: [
              { required: true, message: '请输入用户名' },
            
            ],
          })}
          clear
          placeholder = "用户名"
          error={!!getFieldError('username')}
          onErrorClick={() => {
            alert(getFieldError('username').join('、'));
          }}
          
        >
          <div style={{ backgroundImage: 'url('+ usr_avatar +')' , backgroundSize: 'cover', height: '22px', width: '22px' }} />
        </InputItem>

        <InputItem {...getFieldProps('password',{
            
            rules: [
              { required: true, message: '请输入密码' },
             
            ],
          })}  
          clear
          placeholder = "密码"
          type="password" >
           <div style={{ backgroundImage: 'url('+ pwd_avatar +')' , backgroundSize: 'cover', height: '22px', width: '22px' }} />
        </InputItem>
        
      
        <div className="verifycode">
          <InputItem {...getFieldProps('code',{
              
              rules: [
                { required: true, message: '请输入验证码' },
              
              ],
            })}
            placeholder = "验证码"
            ref = {myRef}
            
            >
              
              <div style={{ backgroundImage: 'url('+ verify_code +')' , backgroundSize: 'cover', height: '20px', width: '20px' }} />
    
          </InputItem>

          <div style={{display:'flex',justifyContent:'center'}}>
            <div style={{ backgroundImage: 'url('+ verifycodeurl +')', backgroundSize: '100% 100%', height: '45px', width: '90px' ,}} 
                  onClick={changeimg}>

            </div>
          </div>
        </div>
       
        <div className="remember">
          <div  className="agreeitem">
            <AgreeItem data-seed="logId" onChange={e => {setrememberMe(e.target.checked)  } } >
            记住我
            </AgreeItem>
          </div>
         
            <div className="regis">
              没有账号？<a onClick={onRegister}>立即注册</a>
            </div>
         
        </div>
        
        

        <Item align="middle" >
          <Button type="primary" onClick={onSubmit}>登录</Button>
          
        </Item>
      </List>

    </div>
  )



}



const BasicInputWrapper = createForm()(BasicInput);




const mapState2Props = (state) => {
  return {
      username : state.getIn(['login','username']),
      pwd : state.getIn(['login','pwd']),
      verifycodeurl : state.getIn(['login','verifycodeurl']),
  }
}

const mapDispatch2Props =  {
    changeimg: LoginAction.refreshimg,
    setusrinfo: LoginAction.setuserinfo,
    seterrorimg :LoginAction.seterrimg
    }



export default connect(mapState2Props,mapDispatch2Props)(BasicInputWrapper)